#include "Myself.h"
#include "ui_Myself.h"
#include "Mainpage.h"
#include <QMessageBox>
#include <QStandardItemModel>
#include <QBitmap>
#include <QStyleOption>
#include "mymessagebox.h"

Myself::Myself(const QString &id, Mainpage *mainpage, QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Myself)
    , mainpageWindow(mainpage)
    , employeeId(id)  // 通过构造函数传递工号
    , tcpSocket(new QTcpSocket(this))
{
    ui->setupUi(this);

    // 隐藏原生标题栏
    setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog);

    // 防止窗口背景透明
    setAttribute(Qt::WA_TranslucentBackground, false);

    // 设置信号槽连接
    connect(tcpSocket, &QTcpSocket::readyRead, this, &Myself::readFromServer);
    connect(ui->group, &QListView::clicked, this, &Myself::on_groupItemClicked);


    // 请求员工信息
    requestEmployeeInfo();

}

Myself::~Myself()
{
    delete ui;
}

// 实现窗口拖动功能
void Myself::mousePressEvent(QMouseEvent *event)
{
    // 检查是否点击了自定义标题栏
    if (event->button() == Qt::LeftButton && event->pos().y() <= 60) {
        m_isTitleBarClicked = true;
        m_dragPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    } else {
        m_isTitleBarClicked = false;
        // 让事件继续传播，确保其他控件能响应点击事件
        QWidget::mousePressEvent(event);
    }
}

void Myself::mouseMoveEvent(QMouseEvent *event)
{
    // 只有在点击了标题栏之后才允许拖动
    if (m_isTitleBarClicked && (event->buttons() & Qt::LeftButton)) {
        move(event->globalPos() - m_dragPosition);
        event->accept();
    } else {
        // 让事件继续传播，确保其他控件能响应移动事件
        QWidget::mouseMoveEvent(event);
    }
}

void Myself::paintEvent(QPaintEvent *event)
{
    // 1. 绘制样式（QSS）
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); // 绘制样式

    // 2. 设置掩码，约定 painter 绘制区域
    QBitmap bmp(this->size());
    bmp.fill(Qt::white); // 填充 bitmap

    QPainter painter(&bmp);
    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::black); // 掩码值
    painter.drawRoundedRect(bmp.rect(), 30, 30); // 在 bitmap 中绘制圆角矩形

    // 设置掩码以确定本控件可绘制区域
    setMask(bmp);

    // 调用基类的 paintEvent
    QWidget::paintEvent(event);
}

void Myself::requestEmployeeInfo()
{
    // 连接到服务器
    tcpSocket->connectToHost("127.0.0.1", 12347);

    if (tcpSocket->waitForConnected(3000)) {
        QString request = QString("GET_EMPLOYEE_INFO|%1").arg(employeeId);
        tcpSocket->write(request.toUtf8());
    } else {
        // QMessageBox::warning(this, "连接失败", "无法连接到服务器");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("连接失败");
        msgBox.setText("无法连接到服务器");
        msgBox.setButton("确定");
        msgBox.exec();
    }

}

void Myself::on_returnButton_clicked()
{
    this->close();
    mainpageWindow->show();
}

void Myself::readFromServer()
{
    QByteArray data = tcpSocket->readAll();
    QString response = QString::fromUtf8(data);

    // 处理服务器响应
    processServerResponse(response);
}

void Myself::processServerResponse(const QString &response)
{
    QStringList parts = response.split("|");

    if (parts.isEmpty()) {
        // QMessageBox::warning(this, "错误", "服务器响应无效");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("服务器响应无效");
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    if (parts[0] == "EMPLOYEE_INFO") {
        // 处理员工信息：工号和姓名
        ui->num->setText(parts[1]);
        ui->name->setText(parts[2]);

        // 将考勤组号列表填充到 QListView 中
        QStandardItemModel *model = new QStandardItemModel(this);
        for (int i = 3; i < parts.size(); ++i) {
            QStandardItem *item = new QStandardItem(parts[i]);
            model->appendRow(item);
        }
        ui->group->setModel(model);

    } else if (parts[0] == "ATTENDANCE_GROUP") {
        // 处理考勤组信息：开始时间、结束时间、考勤日期
        ui->start->setText(parts[1]);
        ui->end->setText(parts[2]);

        // 解析考勤日期并更新 QListView
        updateDateListView(parts[3]);
    }
}

void Myself::on_groupItemClicked(const QModelIndex &index)
{
    QString groupId = index.data().toString();

    // 请求服务器考勤组详细信息
    requestAttendanceGroup(groupId);
}

void Myself::requestAttendanceGroup(const QString &groupId)
{
    QString request = QString("GET_ATTENDANCE_GROUP_INFO|%1").arg(groupId);
    tcpSocket->write(request.toUtf8());
}

void Myself::updateDateListView(const QString &attendanceDays)
{
    // 将考勤日期字符串（例如"0111000"）解析为具体日期
    QStringList daysOfWeek = { "周一", "周二", "周三", "周四", "周五", "周六", "周日" };
    QStandardItemModel *model = new QStandardItemModel(this);

    for (int i = 0; i < attendanceDays.size(); ++i) {
        if (attendanceDays[i] == '1') {
            QStandardItem *item = new QStandardItem(daysOfWeek[i]);
            model->appendRow(item);
        }
    }

    ui->date->setModel(model);
}

void Myself::on_modify_clicked()
{
    // 直接在构造函数中传递工号
    Modify *modify = new Modify(employeeId);
    modify->show();
}

